package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.domain.Course;
import cn.itsource.ymcc.domain.CourseCollect;
import cn.itsource.ymcc.domain.User;
import cn.itsource.ymcc.mapper.CourseCollectMapper;
import cn.itsource.ymcc.producer.CourseMessageProducer;
import cn.itsource.ymcc.result.JsonResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import cn.itsource.ymcc.openfeign.UserOpenfeign;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RocketMQMessageListener(
        consumerGroup = "EmailConsumer",
        topic = CourseMessageProducer.TOPIC_COURSE_SEND_MESSAGE_SMS,
        selectorExpression = CourseMessageProducer.TAGS_COURSE_SEND_MESSAGE_SMS
)
@Slf4j
public class EmailConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private CourseCollectMapper courseCollectMapper;
    @Autowired
    private UserOpenfeign userOpenfeign;
    @Override
    public void onMessage(MessageExt messageExt) {
        Course course = JSON.parseObject(new String(messageExt.getBody()), Course.class);
        sendEmailMessage(course);
    }

    private void sendEmailMessage(Course course) {
        //有一种情况  有些人订阅或者是收藏了的  邮件(一般不看) 短信 站内信(是一个功能  有对应的接口)
        //业务
        List<CourseCollect> courseCollects = courseCollectMapper.selectList(new QueryWrapper<CourseCollect>().eq("course_id", course.getId()));
        if(!courseCollects.isEmpty()){
            for (CourseCollect courseCollect : courseCollects) {
                Long userId = courseCollect.getUserId();
                //远程调用 user服务
                JsonResult jsonResult = userOpenfeign.get(userId);
                String data = (String)jsonResult.getData();
                User user = JSON.parseObject(data, User.class);
//                //调用 短信接口发送短信
//                System.out.println(phone+":你关注的课程已经上线了  你可以通过某地址去观看");
                String email = user.getEmail();
                System.out.println(email+":你关注的课程已经上线了  你可以通过某地址去观看");
//                System.out.println("站内信:你关注的课程已经上线了  你可以通过某地址去观看");
            }
        }
    }
}
